package userDefThreadPool;


public class UserDefThreadPool {

    UserDefBlockingQueue<MyTask> tasks = null;

    private boolean hasClosed = false;

    public UserDefThreadPool(final int poolSize) {
        tasks = new UserDefBlockingQueue<MyTask>();
        for (int startIndex = 1; startIndex <= poolSize; startIndex++) {
            new UserDefPoolThread().start();
        }

    }

    public void execute(final MyTask task) {
        tasks.enque(task);
    }

    public  synchronized void close() {
        hasClosed = true;
       tasks.close();
    }

    class UserDefPoolThread extends Thread {
        @Override
        public void run() {
            while (!UserDefThreadPool.this.hasClosed) {
                try {

                    (tasks.deQueue()).run();

                } catch (final InterruptedException ie) {
                    //Let the thread alive until pool gets closed
                    System.out.println("Thread Interrupted");
                } catch (final ClosedQueueException cqe) {
                    System.out.println("Queue has been closed hence shutting down the thread gracefully");
                }

            }

        }
    }
    
    public static void main(String args[]){
    	UserDefThreadPool test = new UserDefThreadPool(2);
    	for (int i =0; i<10;i++){
    		test.execute(new MyTask("Task"+i));
    	}
    	//test.close();
    }

}
